<?php

namespace Admin\Controller;

class MsgController extends AdminController {

    public function index() {
        $where = '1=1 ';

        $keywords = I('keywords');
        if ($keywords) {
            $where .= " and title like '%" . $keywords . "%'";
            $this->assign('keywords', $keywords);
        }

        //日期选择
        $start_date = I("start_date");
        $end_date = I("end_date");


        if (!empty($end_date) && !empty($start_date)) {
            if ($end_date <= $start_date) {
                $this->error('开始时间不允许小于等于结束时间');
                exit;
            } else {
                $where .= " and create_time between '$start_date 00:00:00' AND '$end_date 23:59:59'";
            }
            $this->assign("start_date", $start_date);
            $this->assign("end_date", $end_date);
        } else {
            if (!empty($start_date)) {
                $where .= " and create_time >='$start_date 00:00:00'";
                $this->assign("start_date", $start_date);
            }

            if (!empty($end_date)) {
                $where .= " and create_time <= '$end_date 23:59:59'";
                $this->assign("end_date", $end_date);
            }
        }

        $M = M('Msg');

        $field = '*';

        $order = "create_time desc";
        $list = $this->lists($M, $where, $order, $field);

        $this->assign('_list', $list);
        $this->assign('meta_title', '消息列表');
        $this->display();
    }

    public function add() {
        $id = I("id", 0, 'intval');
        if (IS_POST) {

            $data['title'] = I("title");
            $data['subtitle'] = I("subtitle");
            $data['content'] = I("content");
            $data['update_time'] = date('Y-m-d H:i:s', time());

            if ($id == 0) {
                $res = M('Msg')->add($data);
            } else {

                $res = M('Msg')->where(array('msg_id' => $id))->save($data);
                $res = $id;
            }

            $user_list = M('Users')->select();

            if (!empty($user_list)) {
                sendjpushbyuser($user_list, ['title' => $data['title'], 'subtitle' => $data['subtitle'], 'msg_url' => "http://" . $_SERVER['HTTP_HOST'] . "/Msg/detail/id/" . $res]);
            }


            if ($res) {
                $this->success('操作成功', U('index'));
            } else {
                $this->error('操作失败');
            }
        } else {
            $data = M('Msg')->where(array("msg_id" => $id))->find();

            $this->assign('data', $data);
            $this->assign('meta_title', '新增/修改消息');
            $this->display();
        }
    }

    public function del() {
        $id = I('id', 0, 'intval');
        if ($id == 0) {
            $this->error('错误的ID');
        }

        $res = M('Msg')->where(array('msg_id' => $id))->delete();

        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

}
